#
# 青少年抑郁症筛查子模块
#


from rasa_sdk.executor import CollectingDispatcher
from typing import Text, Dict, Any, List

from rasa_sdk import Action, Tracker
from rasa_sdk.events import SlotSet, SessionStarted

from actions import common
import time
import requests
import random


def save_end(dispatcher, tracker, text):
    userid = tracker.current_state()['sender_id']
    conn = common.POOL.connection(shareable=False)
    cursor = conn.cursor()
    try:
        y = "update `user_result` set level_of_depression_heart='" + text + "',is_end=1,end_time=now() where `user_info_id` ='" + userid + "'and is_end=0 and topic_type= 2 order by create_time desc limit 1;"
        common.connectmysql(y)
    except:
        dispatcher.utter_message(text='save_error')
    finally:
        cursor.close()
        conn.close()
    return []


class action_show_result(Action):
    def name(self) -> Text:
        return "action_show_result"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        userid = tracker.current_state()['sender_id']
        conn = common.POOL.connection(shareable=False)
        cursor = conn.cursor()
        try:
            cursor.execute(
                "Select * from `user_result` where `user_info_id` = '" + userid + "' and `is_end` = 1 and `topic_type` = 2 order by create_time DESC;")
            x = cursor.fetchone()
            if x[6] == '' or x[6] is None:
                dispatcher.utter_message(text='天啦噜，诊断结果拿不到啦')
            else:
                dispatcher.utter_message(text="你的诊断结果是：" + x[6])
                if common.openexpert(userid):
                    t = common.getuserinfo(userid)
                    wxopenid = t[16]
                    dispatcher.utter_message(text='''不用担心哦~我会和很多叫做“心理专家”的两脚兽一直陪着你的~''', buttons=[
                        {"payload": "/greet", "title": "返回首页"},{'payload':f'WXUserApplyConsult&{wxopenid}', 'title':f'我还有问题，申请人工咨询', 'view':'申请专家咨询', 'type':"weixin", 'life':1} ])
                else:
                    dispatcher.utter_message(text='''不用担心哦~我会和很多叫做“心理专家”的两脚兽一直陪着你的~''', buttons=[
                        {"payload": "/greet", "title": "返回首页"}, ])
        except Exception as e:
            # return response.json({"error": e})
            pass
        finally:
            cursor.close()
            conn.close()
        return [SessionStarted()]


class action_not_show_result(Action):
    def name(self) -> Text:
        return "action_not_show_result"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        userid = tracker.current_state()['sender_id']
        dispatcher.utter_message(text="好的~和你聊天真开心~")
        if common.openexpert(userid):
            t = common.getuserinfo(userid)
            wxopenid = t[16]
            dispatcher.utter_message(text='''接下来我会和很多叫做“心理专家”的两脚兽一直陪着你哦~''', buttons=[
            {"payload": "/greet", "title": "返回首页"},{'payload':f'WXUserApplyConsult&{wxopenid}', 'title':f'我还有问题，申请人工咨询', 'view':'申请专家咨询', 'type':"weixin", 'life':1} ])
        else:
            dispatcher.utter_message(text='''接下来我会和很多叫做“心理专家”的两脚兽一直陪着你哦~''', buttons=[
            {"payload": "/greet", "title": "返回首页"}, ])
        return [SessionStarted()]


class action_depression_sad(Action):
    def name(self) -> Text:
        return "action_depression_sad"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        text = "悲伤、丧痛"
        a = save_end(dispatcher, tracker, text)
        dispatcher.utter_message(text="呜呼……所有的问题都问完啦~")
        dispatcher.utter_message(text="你想要看看最终的诊断结果吗？", buttons=[
            {"payload": "/result_yes", "title": "想看想看！", "life": 1},
            {"payload": "/result_no", "title": "不要了吧", "life": 1},
        ])
        return a


class action_depression_reactive_state(Action):
    def name(self) -> Text:
        return "action_depression_reactive_state"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        text = "反应性状态/适应障碍"
        a = save_end(dispatcher, tracker, text)
        dispatcher.utter_message(text="呜呼……所有的问题都问完啦~")
        dispatcher.utter_message(text="你想要看看最终的诊断结果吗？", buttons=[
            {"payload": "/result_yes", "title": "想看想看！", "life": 1},
            {"payload": "/result_no", "title": "不要了吧", "life": 1},
        ])
        return a


class action_biphasic(Action):
    def name(self) -> Text:
        return "action_biphasic"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        text = "双相、对立违抗障碍、自闭谱系、间歇性暴怒障碍"
        a = save_end(dispatcher, tracker, text)
        dispatcher.utter_message(text="呜呼……所有的问题都问完啦~")
        dispatcher.utter_message(text="你想要看看最终的诊断结果吗？", buttons=[
            {"payload": "/result_yes", "title": "想看想看！", "life": 1},
            {"payload": "/result_no", "title": "不要了吧", "life": 1},
        ])
        return a


class action_depression_destructive(Action):
    def name(self) -> Text:
        return "action_depression_destructive"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        text = "破坏性心境状态"
        a = save_end(dispatcher, tracker, text)
        dispatcher.utter_message(text="呜呼……所有的问题都问完啦~")
        dispatcher.utter_message(text="你想要看看最终的诊断结果吗？", buttons=[
            {"payload": "/result_yes", "title": "想看想看！", "life": 1},
            {"payload": "/result_no", "title": "不要了吧", "life": 1},
        ])
        return a


class action_physical_problem(Action):
    def name(self) -> Text:
        return "action_physical_problem"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        text = "其他躯体问题，或者物质滥用障碍等"
        a = save_end(dispatcher, tracker, text)
        dispatcher.utter_message(text="呜呼……所有的问题都问完啦~可把我累坏了……")
        dispatcher.utter_message(text="你想要看看最终的诊断结果吗？", buttons=[
            {"payload": "/result_yes", "title": "想看想看！", "life": 1},
            {"payload": "/result_no", "title": "不要了吧", "life": 1},
        ])
        return a


class action_neurocognitive_impairment(Action):
    def name(self) -> Text:
        return "action_neurocognitive_impairment"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        text = "神经认知障碍伴行为紊乱"
        a = save_end(dispatcher, tracker, text)
        dispatcher.utter_message(text="呜呼……所有的问题都问完啦~可把我累坏了……")
        dispatcher.utter_message(text="你想要看看最终的诊断结果吗？", buttons=[
            {"payload": "/result_yes", "title": "想看想看！", "life": 1},
            {"payload": "/result_no", "title": "不要了吧", "life": 1},
        ])
        return a


class action_mood_swings(Action):
    def name(self) -> Text:
        return "action_mood_swings"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        text = "情绪波动"
        a = save_end(dispatcher, tracker, text)
        dispatcher.utter_message(text="呜呼……所有的问题都问完啦~")
        dispatcher.utter_message(text="你想要看看最终的诊断结果吗？", buttons=[
            {"payload": "/result_yes", "title": "想看想看！", "life": 1},
            {"payload": "/result_no", "title": "不要了吧", "life": 1},
        ])
        return a


class action_seasonal_depressive_state(Action):
    def name(self) -> Text:
        return "action_seasonal_depressive_state"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        text = "季节性抑郁状态"
        a = save_end(dispatcher, tracker, text)
        dispatcher.utter_message(text="呜呼……所有的问题都问完啦~可把我累坏了……")
        dispatcher.utter_message(text="你想要看看最终的诊断结果吗？", buttons=[
            {"payload": "/result_yes", "title": "想看想看！", "life": 1},
            {"payload": "/result_no", "title": "不要了吧", "life": 1},
        ])
        return a


class action_premenstrual_low_mood(Action):
    def name(self) -> Text:
        return "action_premenstrual_low_mood"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        text = "经前期心境恶劣状态"
        a = save_end(dispatcher, tracker, text)
        dispatcher.utter_message(text="呜呼……所有的问题都问完啦~可把我累坏了……")
        dispatcher.utter_message(text="你想要看看最终的诊断结果吗？", buttons=[
            {"payload": "/result_yes", "title": "想看想看！", "life": 1},
            {"payload": "/result_no", "title": "不要了吧", "life": 1},
        ])
        return a


class action_period_pain(Action):
    def name(self) -> Text:
        return "action_period_pain"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        text = "经前综合征、痛经"
        a = save_end(dispatcher, tracker, text)
        dispatcher.utter_message(text="呜呼……所有的问题都问完啦~可把我累坏了……")
        dispatcher.utter_message(text="你想要看看最终的诊断结果吗？", buttons=[
            {"payload": "/result_yes", "title": "想看想看！", "life": 1},
            {"payload": "/result_no", "title": "不要了吧", "life": 1},
        ])
        return a


class action_biphasic_state_or_circular_mood(Action):
    def name(self) -> Text:
        return "action_biphasic_state_or_circular_mood"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        text = "双相状态或环型心境"
        a = save_end(dispatcher, tracker, text)
        dispatcher.utter_message(text="呜呼……所有的问题都问完啦~可把我累坏了……")
        dispatcher.utter_message(text="你想要看看最终的诊断结果吗？", buttons=[
            {"payload": "/result_yes", "title": "想看想看！", "life": 1},
            {"payload": "/result_no", "title": "不要了吧", "life": 1},
        ])
        return a


class action_major_depressive_state(Action):
    def name(self) -> Text:
        return "action_major_depressive_state"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        text = "重性抑郁状态"
        a = save_end(dispatcher, tracker, text)
        dispatcher.utter_message(text="呜呼……所有的问题都问完啦~可把我累坏了……")
        dispatcher.utter_message(text="你想要看看最终的诊断结果吗？", buttons=[
            {"payload": "/result_yes", "title": "想看想看！", "life": 1},
            {"payload": "/result_no", "title": "不要了吧", "life": 1},
        ])
        return a


class action_persistent_depression(Action):
    def name(self) -> Text:
        return "action_persistent_depression"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        text = "持续性抑郁状态（心境恶劣）"
        a = save_end(dispatcher, tracker, text)
        dispatcher.utter_message(text="呜呼……所有的问题都问完啦~可把我累坏了……")
        dispatcher.utter_message(text="你想要看看最终的诊断结果吗？", buttons=[
            {"payload": "/result_yes", "title": "想看想看！", "life": 1},
            {"payload": "/result_no", "title": "不要了吧", "life": 1},
        ])
        return a


def midterm_encourage(dispatcher, tracker):
    try:
        i = random.randint(1, 5)
        url = 'https://obs-e912.obs.cn-east-2.myhuaweicloud.com/zy_xm/image/rasa_photo_2021_08_16/encourage/encourage_' + str(
            i) + '.jpg'
        # pic_url = re.findall('"objURL":"(.*?)"', result.text, re.S)  # 正则出很多张图片的url
        # i = random.randint(0, 3)
        dispatcher.utter_message(text='呼~好累呀……但是马上就问完啦，小E要加油！加油！！💪💪', image=url)
    except:
        dispatcher.utter_message(text='呼~好累呀……但是马上就问完啦，小E要加油！加油！！💪💪')
    return []
